setwd("/home/uec-00/yapingli/code/Allele_specific_methylation/")
for(i in c("normal","tumor")){
	for(j in c(1:22,"X","Y")){
		fileName=paste("methylCGsRich_ASM_AllSnp_",i,"Merge_chr",j,"_table.txt",sep="")
		x<-read.table(fileName,header=F,sep="\t")
		ASM<-array()
		i=1
		while(i<=length(x[,2])){
			temp<-x[i,1]
			y<-x[x[,1]==temp,]
			minRange<-min(y[,2])
			maxRange<-max(y[,2])
			region=paste(minRange,maxRange,sep="~")
			A<-c(y[,3],y[,4])
			B<-c(y[,5],y[,6])
			p<-fisher.test(rbind(A,B),workspace = 2000000000)
			logP<-log2(p$p.value)
			methy_A=0
			methy_B=0
			for(j in c(1:length(y[,2]))){
				methy_A <- methy_A + y[j,3]/(y[j,3]+y[j,4])
				methy_B <- methy_B + y[j,5]/(y[j,5]+y[j,6])
			}
			methy_ratio=0
			ifelse(methy_B != 0,methy_ratio<-methy_A/methy_B,methy_ratio<-c(1000))

			thisRow<-cbind(temp,region,length(y[,2]),methy_ratio,p$p.value)
			ASM<-rbind(ASM,thisRow)

			i<-i+length(y[,2])
		}

		pAdjust<-p.adjust(as.numeric(ASM[,4]),method="BH")
		pAdjustLog<-log2(pAdjust)
		ASM<-cbind(ASM,pAdjust)
		outputName=paste("methylCGsRich_ASM_AllSnp_",i,"Merge_chr",j,"_pValue_ASMblock.txt",sep="")
		write.table(output, outputName,sep="\t",quote=F,col.names=F,row.names=F)
	}
}


